import axios from 'axios'
import { Message, Loading } from 'element-ui'
import { removeToken } from '@/utils/auth'
import router from '@/router'
import i18n from '@/utils/i18n'
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_PREFIX, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    crossDomain: true,
    timeout: 30000 // request timeout
})

let requestLoading

const loadList = [
    '530012', '530058'
]
let urlc
// request interceptor
service.interceptors.request.use(
    config => {
        // console.log(config);
        const shopId = localStorage.getItem('shopId') || ''
        urlc = config.url.split('do?c=')[1]
        if (shopId && shopId !== 'null' && shopId !== 'undefined') {
            // 加载
            if (loadList.includes(urlc)) {
                requestLoading = Loading.service()
            }
            config.headers.version = 'DD_2.2.2'
            config.headers.language = i18n.locale
            config.headers.shopId = localStorage.getItem('shopId')
            return config
        } else {
            config.headers.version = 'DD_2.2.2'
            config.headers.shopId = '1'
            config.headers.language = i18n.locale
            return config
            // Message.error('没有shopId')
        }
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
    */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data

        if (loadList.includes(urlc)) {
            requestLoading.close()
        }

        if (res.errorCode !== '000000' && res.success != true) {
            Message({
                message: res.errorMsg || 'Error',
                type: 'error',
                duration: 3 * 1000
            })
            if (res.errorCode === '00016' || res.errorCode === '00068') {
                removeToken()
                // debugger
                sessionStorage.clear()
                localStorage.clear()
                router.replace(`/login`)
            }
            return Promise.reject(new Error(res.errorMsg || 'Error'))
        } else {
            return Promise.resolve(res)
        }
    },
    error => {
        if (loadList.includes(urlc)) {
            requestLoading.close()
        }
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
